﻿#region << 文 件 说 明 >>

/*----------------------------------------------------------------
// 文件名称：VampirewalConfig
// 创 建 者：杨程
// 创建时间：2021/9/24 11:10:56
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//
//
//----------------------------------------------------------------*/

#endregion



namespace Vampirewal.Core.Components;

/// <summary>
/// Vampirewal使用的config
/// </summary>
[Obsolete("20230128切换使用新的配置文件方式", true)]
internal sealed class VampirewalConfig : IAppConfig
{
    /// <summary>
    /// 日志级别
    /// </summary>
    public LoggerType LogLevel { get; set; } = LoggerType.Debug;

    /// <summary>
    /// app中文名
    /// </summary>
    public string AppChineseName { get; set; }//展示界面顶部的名称

    /// <summary>
    /// 程序本地版本
    /// </summary>
    public string AppVersion { get; set; } = "1.0.0.0";

    #region 连接字符串集合

    private List<ConnectionString> _connectStrings;

    /// <summary>
    /// 连接字符串集合
    /// </summary>
    public List<ConnectionString> ConnectionStrings
    {
        get
        {
            return _connectStrings ??= new List<ConnectionString>();
        }
        set
        {
            _connectStrings = value;
        }
    }

    #endregion

    #region 数据库类型

    private DBTypeEnum? _dbtype;

    /// <summary>
    /// 数据库类型
    /// </summary>
    public DBTypeEnum DbType
    {
        get
        {
            return _dbtype ?? DBTypeEnum.SqlServer;
        }
        set
        {
            _dbtype = value;
        }
    }

    #endregion

    #region 加密密钥

    private string _encryptKey;

    /// <summary>
    /// 加密密钥
    /// </summary>
    public string EncryptKey
    {
        get
        {
            if (string.IsNullOrEmpty(_encryptKey))
            {
                _encryptKey = string.Empty;
            }
            return _encryptKey;
        }
        set
        {
            _encryptKey = value;
        }
    }

    #endregion

    #region 自定义设置

    private Dictionary<string, string> _appSettings;

    /// <summary>
    /// 自定义设置
    /// </summary>
    public Dictionary<string, string> AppSettings
    {
        get
        {
            return _appSettings ?? new Dictionary<string, string>();
        }
        set
        {
            _appSettings = value;
        }
    }

    #endregion

    #region 附件上传设置

    /// <summary>
    /// 附件上传设置
    /// </summary>
    public FileUploadOptions FileUploadOptions { get; set; } = new FileUploadOptions()
    {
        SaveFileMode = SaveFileModeEnum.Local,
        UploadDir = DefaultConfigConsts.DEFAULT_UPLOAD_DIR,
        UploadLimit = DefaultConfigConsts.DEFAULT_UPLOAD_LIMIT
    };

    #endregion

    #region 视图View模块dll路径

    private List<string> _ViewModulesPath;

    /// <summary>
    /// 视图View模块dll路径
    /// </summary>
    public List<string> ViewModulesPath
    {
        get
        {
            return _ViewModulesPath ?? new List<string>();
        }
        set
        {
            _ViewModulesPath = value;
        }
    }

    #endregion

    #region 连接域设置

    private List<DomainSetting> _Domains;

    /// <summary>
    /// 连接域
    /// </summary>
    public List<DomainSetting> Domains
    {
        get
        {
            return _Domains ?? new List<DomainSetting>();
        }
        set
        {
            _Domains = value;
        }
    }

    #endregion

    #region 操作

    /// <summary>
    /// 配置文件路径
    /// </summary>
    [JsonIgnore]
    public string ConfigPath { get; set; } = AppDomain.CurrentDomain.BaseDirectory;

    /// <summary>
    /// 配置文件名称
    /// </summary>
    [JsonIgnore]
    public string ConfigName { get; set; } = "AppConfig.json";

    /// <summary>
    /// 更新程序设置
    /// </summary>
    public UpdateSetting UpdateSetting { get; set; } = new UpdateSetting()
    {
        UpdateName = "XX",
        ServerIp = "127.0.0.1",
        ServerPort = "1234",
        AppToken = "aaaa"
    };

    /// <summary>
    /// 分页设置
    /// </summary>
    public PageSetting pageSetting { get; set; } = new PageSetting()
    {
        Limit = DefaultConfigConsts.DEFAULT_RPP
    };

    /// <summary>
    /// 读取配置文件
    /// </summary>
    public void LoadAppConfig()
    {
        //var configFile = $"{AppDomain.CurrentDomain.BaseDirectory}AppConfig.json";
        var configFile = $"{ConfigPath}\\{ConfigName}";

        if (File.Exists(configFile))
        {
            var Config = JsonConvert.DeserializeObject<VampirewalConfig>(JsonHelper.Readjson(configFile));
            SetValue(Config);

            ExcuteLoadAssembly(isLoad);
        }
        else
        {
            //T t = new T();
            //var json = JsonConvert.SerializeObject(t);
            //var formatStr = JsonHelper.FormatJsonString(json);
            //FileStream fs = File.Create(configFile);
            //fs.Dispose();
            //File.AppendAllText(configFile, formatStr);

            //Config = t;

            Save();
            var Config = JsonConvert.DeserializeObject<VampirewalConfig>(JsonHelper.Readjson(configFile));
            SetValue(Config);
        }
    }

    private void SetValue(VampirewalConfig self)
    {
        LogLevel = self.LogLevel;
        AppChineseName = self.AppChineseName;
        AppVersion = self.AppVersion;
        ConnectionStrings = self.ConnectionStrings;
        DbType = self.DbType;
        AppSettings = self.AppSettings;
        EncryptKey = self.EncryptKey;
        FileUploadOptions = self.FileUploadOptions;
        UpdateSetting = self.UpdateSetting;
        pageSetting = self.pageSetting;
        ViewModulesPath = self.ViewModulesPath;
        Domains = self.Domains;
    }

    /// <summary>
    /// 保存
    /// </summary>
    public void Save()
    {
        var jsonStr = JsonConvert.SerializeObject(this);
        var formatStr = JsonHelper.FormatJsonString(jsonStr);
        //var configFile = $"{AppDomain.CurrentDomain.BaseDirectory}AppConfig.json";
        var configFile = $"{ConfigPath}\\{ConfigName}";
        if (File.Exists(configFile))
        {
            File.Delete(configFile);
        }
        if (!Directory.Exists(ConfigPath))
        {
            Directory.CreateDirectory(ConfigPath);
        }
        File.AppendAllText(configFile, formatStr);
    }

    /// <summary>
    /// 重置配置文件（慎用）
    /// </summary>
    public void Reset()
    {
        //var configFile = $"{AppDomain.CurrentDomain.BaseDirectory}AppConfig.json";
        var configFile = $"{ConfigPath}\\{ConfigName}";
        if (File.Exists(configFile))
        {
            File.Delete(configFile);

            LoadAppConfig();
        }
    }

    private bool isLoad = false;

    private void ExcuteLoadAssembly(bool _isLoaded)
    {
        if (!_isLoaded && ViewModulesPath.Count > 0)
        {
            ViewModulesPath.ForEach(f =>
            {
                try
                {
                    Assembly ass = Assembly.LoadFile(f);
                }
                catch
                {
                    //ErrorStr.Add($"无法加载该dll-{f}");
                    throw new Exception($"无法加载该DLL：{f}");
                }
            });

            isLoad = true;
        }
    }

    #endregion
}





